import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { RegisterDto } from './dto/register.dto';
import { UserEntity } from '@/entity/user.entity';

@Injectable()
export class AuthService {
  constructor(
    private jwtService: JwtService,
    @InjectRepository(UserEntity)
    private userRepository: Repository<UserEntity>,
  ) {}

  //注册
  async register(createUser: RegisterDto) {
    const { username } = createUser;
    const existUser = await this.userRepository.findOne({
      where: { username },
    });
    if (existUser) {
      throw new HttpException('用户名已存在', HttpStatus.BAD_REQUEST);
    }
    const newUser = await this.userRepository.create(createUser);
    //返回保护后的数据
    return await this.userRepository.save(newUser);
  }

  // 生成token
  createToken(user: Partial<UserEntity>) {
    return this.jwtService.sign(user);
  }

  // 登录
  async login(user: Partial<UserEntity>) {
    const token = this.createToken({
      user_id: user.user_id,
      username: user.username,
      role: user.role,
    });
    return { token };
  }

  // 验证用户
  async validateUser({ user_id }: Partial<UserEntity>) {
    return await this.userRepository.findOne({ where: { user_id: user_id } });
  }

  // 验证用户是否存在
  async validateUserExist({ user_id }: Partial<UserEntity>) {
    const user = await this.userRepository.findOne({
      where: { user_id: user_id },
    });
    if (!user) {
      throw new HttpException('用户不存在', HttpStatus.BAD_REQUEST);
    }
    return true;
  }
}
